package com.project.springboot.page;

import com.gitee.yongzhuzl.commonutil.util.empty.EmptyUtil;
import com.project.springboot.exception.ResponseException;
import org.apache.commons.lang3.StringUtils;

/**
 * description: sql过滤
 * @author 朱正磊
 * @date 2023-08-09 23:09:01
 */
public class SqlFilter {

    /**
     * description: sql注入过滤
     * @author 朱正磊
     * @date 2023-07-06 17:48:01
     * @param sqlStr 待验证的字符串
     * @return 返回经过处理的字符串
     */
    public static String sqlInject(String sqlStr) {
        if (EmptyUtil.isEmpty(sqlStr)) {
            return null;
        }

        // 去掉'|"|;|\字符
        sqlStr = StringUtils.replace(sqlStr, "'", "");
        sqlStr = StringUtils.replace(sqlStr, "\"", "");
        sqlStr = StringUtils.replace(sqlStr, ";", "");
        sqlStr = StringUtils.replace(sqlStr, "\\", "");

        // 转换成小写
        sqlStr = sqlStr.toLowerCase();

        // 非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};

        // 判断是否包含非法字符
        for (String keyword : keywords) {
            if (sqlStr.contains(keyword)) {
                throw new ResponseException("包含非法字符！");
            }
        }

        return sqlStr;
    }

}
